package etnorservice.etnor_service.utils;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ServerStatusChecker {

    /**
     * 检查服务器是否可达
     *
     * @param serverHost 服务器地址
     * @return 如果服务器可达，返回true，否则返回false
     */
    public static boolean isServerReachable(String serverHost) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(serverHost, 22), 2000); // 22是SSH端口，2000是超时毫秒数
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 检查服务器上的端口是否开放
     *
     * @param serverHost 服务器地址
     * @param port       要检查的端口号
     * @return 如果端口开放，返回true，否则返回false
     */
    public static boolean isPortOpen(String serverHost, int port) {
        if (!isServerReachable(serverHost)) {
            throw new IllegalArgumentException("Server is not reachable: " + serverHost);
        }

        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(serverHost, port), 2000); // 超时毫秒数
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
